<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'
import { getCustomer, Customer, pauseRecordingType } from '@/api/customer'
import AddCustomerVue from './CustomerOptionDialog.vue'
import TableOption from '@/components/TableOption.vue'
import { EnumType } from '@/consts/public'
import { DistributionEnum } from '@/consts/Customer'
import { formattingTime, isInScope, getShippedNumber } from '@/common/Calculate'

const distributionEnumList: EnumType[] = Object.values(DistributionEnum)

const props = defineProps({
  isAllowAddCustomer: { // 是否允许添加客户
    type: Boolean,
    default: false
  },
  isFilterExpired: { // 是否过滤已到期用户
    type: Boolean,
    default: false
  }
})

// 客户列表
const tableData = ref<Customer[]>()
const paginationVal = reactive({
  currentPage: 1,
  total: 0,
  limit: 10
})

const tableRowClassName = ({ row }: { row: Customer, rowIndex: number}) => {
  const { amount, pause_recording: pauseRecording } = row
  const number = shippedNumber(row)
  const date = new Date()
  const stop = pauseRecording && JSON.parse(pauseRecording).find((item: pauseRecordingType) => {
    const { stopTime, endStopTime } = item
    return isInScope(formattingTime(date), stopTime, endStopTime)
  })
  if (stop) {
    return 'danger-row'
  }
  if (amount === number) {
    return 'info-row'
  } else if (amount - number < 2) {
    return 'warning-row'
  }
  return ''
}

const getTableData = async () => {
  try {
    const param = {
      pagination: {
        currentPage: paginationVal.currentPage,
        limit: paginationVal.limit
      },
      [searchWay.value]: searchValue.value,
      filterExpired: props.isFilterExpired
    }
    const { data, pagination } = await getCustomer(param)
    const { currentPage, total, limit } = pagination
    tableData.value = data
    paginationVal.currentPage = currentPage
    paginationVal.limit = limit
    paginationVal.total = total
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const distributionFormatter = (row: Customer, column: unknown, cellValue: number) => {
  return distributionEnumList.find(item => item.value === cellValue)?.label
}

const addressFormatter = (row: Customer) => {
  const { address, detailed_address } = row
  return address + (detailed_address || '')
}

const shippedNumber = (row: Customer) => {
  const { start_time, amount, distribution, pause_recording } = row
  return getShippedNumber(start_time, amount, distribution, pause_recording)
}

const stopNumber = (row: Customer) => (JSON.parse(row.pause_recording)?.length || 0)

const handleCurrentChange = async (val: number) => {
  paginationVal.currentPage = val
  await getTableData()
}

// 查找
const optionsList: EnumType[] = [
  {
    label: '姓名',
    value: 'name'
  },
  {
    label: '手机号',
    value: 'phone'
  },
  {
    label: '地址',
    value: 'address'
  }
]
const searchValue = ref('')
const searchWay = ref('name')

const search = async (prarm: object) => {
  searchWay.value = Object.keys(prarm)[0]
  searchValue.value = Object.values(prarm)[0]
  await getTableData()
}

// 新增客户
const showAddDialog = ref(false)
const addSuccess = async () => {
  await getTableData()
  showAddDialog.value = false
}

// 生命周期
onMounted(async () => {
  await getTableData()
})

defineExpose({ getTableData })
</script>

<template>
  <el-card shadow="Never">
    <TableOption
      :optionsList=optionsList
      :showButtons="props.isAllowAddCustomer"
      defaultButtonText="新增客户"
      @search="search"
      @defaultButtonoption="showAddDialog = true"
    />
    <el-space class="tip" :size="36">
      <div class="tip-box">
        <span class="tip-text">今日停送：</span><i class="tip-i danger" />
      </div>
      <div class="tip-box">
        <span class="tip-text">即将到期：</span><i class="tip-i warning" />
      </div>
      <div class="tip-box">
        <span class="tip-text">已到期：</span><i class="tip-i info" />
      </div>
    </el-space>
    <el-table :data="tableData"
      :border="true" size="small"
      style="width: 100%"
      :row-key="(row: Customer) => row.id"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="name" label="姓名" width="80" />
      <el-table-column prop="products_name" label="订购产品" min-width="200" />
      <el-table-column prop="amount" label="订购瓶数" width="80" />
      <el-table-column prop="distribution" label="配送方式" width="80" :formatter="distributionFormatter" />
      <el-table-column label="已配送瓶数" width="100" :formatter="shippedNumber" />
      <el-table-column prop="phone" label="手机号" width="100" />
      <el-table-column prop="address" label="配送地址" min-width="200" :formatter="addressFormatter"/>
      <slot>
          <el-table-column label="停送次数" min-width="80" :formatter="stopNumber"/>
          <el-table-column prop="start_time" label="起送时间" width="120"/>
          <el-table-column prop="end_time" label="到期时间" width="120"/>
          <el-table-column prop="created_at" label="创建时间" width="160"/>
      </slot>
      <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <slot name="option" :scope="scope" />
          </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination">
      <el-pagination
        v-model:currentPage="paginationVal.currentPage"
        v-model:page-size="paginationVal.limit"
        background
        layout="prev, pager, next, jumper"
        :total="paginationVal.total"
        @current-change="handleCurrentChange"
      />
    </div>
    <AddCustomerVue
      v-model="showAddDialog"
      @closeDialog="showAddDialog = false"
      @optionSuccess="addSuccess"
      />
  </el-card>
</template>

<style lang="scss" scoped>
::v-deep .el-table .danger-row {
  --el-table-tr-bg-color: var(--el-color-danger-light-7);
}
::v-deep .el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-7);
}
::v-deep .el-table .info-row {
  --el-table-tr-bg-color: var(--el-color-info-light-7);
}
.tip {
  display: flex;
  justify-content: flex-end;
  height: 20px;
  margin-bottom: 20px;
  &-box {
    display: flex;
    align-items: center;
  }
  &-text {
    font-size: 12px;
    color: #909399;
  }
  &-i {
    display: inline-block;
    width: 80px;
    height: 20px;
  }
  .danger {
    background-color: var(--el-color-danger-light-7);
  }
  .warning {
    background-color: var(--el-color-warning-light-7);
  }
  .info {
     background-color: var(--el-color-info-light-7);
  }
}
.demo-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}
.option-panel {
  display: flex;
  justify-content: space-between;
  width: 500xp;
  margin-bottom: 20px;
  .search-input {
    width: 500px;
  }
}
</style>
